<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use JWTAuth;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\JsonResponse;
//use Tymon\JWTAuth\Facades\JWTAuth;


class UsersController extends Controller
{

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * 请求头
     *  Authorization：$token
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $data = $request->input();
        $account = $data['account'];

        //方式一
        //$token = JWTAuth::fromUser($user);
        //方式二
        //$token = auth('api')->login($user);
        //方式三、下面这种方式必须使用密码登录
        $token=auth('api')->attempt($data);
        if(!$token){
            return response()->json(['error' => 'Unauthorized'],401);
        }

        $user = Users::where(['account'=>$account])->first();

        if($user){
            return $this->respondWithToken($token,$user);
        }
        return response()->json(['error' => '登录失败'],401);
    }

    /**
     * 注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function SignUp(Request $request)
    {
        $validate=Validator::make($request->all(), [
            'account' => 'required|max:255',
            'password' => 'required|alpha_num',
        ]);
        // 验证未通过重定向到指定界面，并提示错误信息
        if ($validate->fails()) {
            return $validate->errors();
        }

        $data['account'] = $request['account'];
        $data['password'] = $request['password'];
        //以手机号登录测试，具体根据自己的业务逻辑
        $user = Users::where(['account' => $data['account']])->first();

        if($user){
            return response()->json(['error' => '已经注册过了'],401);
        }

        $UsersModel = new Users();
        if(!$user){
            $addData=[
                'account'=> $data['account'],
                'name'=> $data['account'],
                'email'=> $data['account'],
                'password'=>bcrypt($data['password']),
            ];
            $UsersModel->insert($addData);
        }

        return response()->json(['error' => '注册成功'],200);
    }

    protected function respondWithToken($token, $data)
    {
        $data['access_token']=$token;
        $data['token_type']='bearer '.$token;
        $data['expires_in']=auth('api')->factory()->getTTL()*60;
        return response()->json([
            'code' => 0,
            'msg' => '登录成功',
            'data' => $data,
        ]);
    }

    /*获取用户信息*/
    public function get_user_details(Request $request)
    {
        $user = JWTAuth::toUser(JWTAuth::getToken());
        return response()->json(['result' => $user]);
    }

    public function quitLogin()
    {
        JWTAuth::invalidate(JWTAuth::getToken());
        return response()->json(['msg' =>'退出成功']);
    }

}
